<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Db;
/**
 * 用户业务权限默认控制器
 * @package app\user\admin
 */
class AccessManage extends Admin
{
    
    /**
     * 权限管理
     * @param string $group 分组
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function index($group = 'area')
    {   
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $map = $this->getMap();
        $order = $this->getOrder('a.id asc');
        $userid=input('userid',0,'intval');
        $map['a.userid']=$userid;

        // 配置分组信息
        $list_group = ['area' =>'区域', 'warehouse' => '仓库', 'member' => '客户', 'store' => '货主'];
        $tab_list = [];
        foreach ($list_group as $key => $value) {
            $tab_list[$key]['title'] = $value;
            $tab_list[$key]['url']   = url('index', ['userid'=>$userid,'group' => $key]);
        }

        switch ($group) {
            case 'area':
                // 数据列表
                $data_list = db("admin_access_area a")->join("admin_area b","a.provinceid=b.id","left")->where($map)->order($order)->field("a.*,b.name as provincename")->paginate();
                // 分页数据
                $page = $data_list->render();
                $list_province = db("admin_area")->where("pid=0")->column("id,name");
                // 使用ZBuilder快速创建数据表格
                return ZBuilder::make('table')
                    ->setPageTitle('业务区域') // 设置页面标题
                    ->setTabNav($tab_list, $group) // 设置tab分页
                    ->setTableName('admin_access_area') // 设置数据表名
                    ->setPrimaryKey("id")
                    ->setSearch(['id' => '编号', 'provincename' => '省/直辖市']) // 设置搜索参数
                    ->addColumns([ // 批量添加列
                        ['id', '编号'],
                        ['provinceid', '省/直辖市','select',$list_province],
                        ['status', '状态', 'switch'],
                        ['right_button', '操作', 'btn']
                    ])
                    ->addTopButton('add',['href' => url('areaadd',['userid'=>$userid])]) // 批量添加顶部按钮
                    ->addOrder(['listorder', 'id'])
                    ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('areaedit', ['id' => '__id__'])])
                    ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('areadelete', ['id' => '__id__'])])
                    ->setRowList($data_list) // 设置表格数据
                    ->setPages($page) // 设置分页数据
                    ->fetch(); // 渲染页面
                break;
            case 'warehouse':
                // 数据列表
                $data_list = db("admin_access_warehouse a")->join("warehouse_list b","a.warehouseid=b.warehouseid","left")->where($map)->order($order)->field("a.*,b.warehousename")->paginate();
                // 分页数据
                $page = $data_list->render();

                $list_warehouse = db("warehouse_list")->where("status=1 and isdel=0")->column("warehouseid,warehousename");
                // 使用ZBuilder快速创建数据表格
                return ZBuilder::make('table')
                    ->setPageTitle('业务仓库') // 设置页面标题
                    ->setTabNav($tab_list, $group) // 设置tab分页
                    ->setTableName('admin_access_warehouse') // 设置数据表名
                    ->setPrimaryKey("id")
                    ->setSearch(['id' => '编号', 'warehousename' => '仓库名称']) // 设置搜索参数
                    ->addColumns([ // 批量添加列
                        ['id', '编号'],
                        ['warehouseid', '仓库名称','select',$list_warehouse],
                        ['status', '状态', 'switch'],
                        ['right_button', '操作', 'btn']
                    ])
                    ->addTopButton('add',['href' => url('warehouseadd',['userid'=>$userid])]) // 批量添加顶部按钮
                    ->addOrder(['listorder', 'id'])
                    ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('warehouseedit', ['id' => '__id__'])])
                    ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('warehousedelete', ['id' => '__id__'])])
                    ->setRowList($data_list) // 设置表格数据
                    ->setPages($page) // 设置分页数据
                    ->fetch(); // 渲染页面
                break;
            case 'member':
                // 数据列表
                $data_list = db("admin_access_member a")->join("member b","a.memberid=b.id","left")->where($map)->order($order)->field("a.*,b.Name as membername")->paginate();
                // 分页数据
                $page = $data_list->render();
                // 使用ZBuilder快速创建数据表格
                return ZBuilder::make('table')
                    ->setPageTitle('业务客户') // 设置页面标题
                    ->setTabNav($tab_list, $group) // 设置tab分页
                    ->setTableName('admin_access_member') // 设置数据表名
                    ->setPrimaryKey("id")
                    ->setSearch(['id' => '编号', 'membername' => '客户名称']) // 设置搜索参数
                    ->addColumns([ // 批量添加列
                        ['id', '编号'],
                        ['membername', '客户名称'],
                        ['status', '状态', 'switch'],
                        ['right_button', '操作', 'btn']
                    ])
                    ->addTopButton('add',['href' => url('memberadd',['userid'=>$userid])]) // 批量添加顶部按钮
                    ->addOrder(['listorder', 'id'])
                    ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('memberedit', ['id' => '__id__'])])
                    ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('memberdelete', ['id' => '__id__'])])
                    ->setRowList($data_list) // 设置表格数据
                    ->setPages($page) // 设置分页数据
                    ->fetch(); // 渲染页面
                break;
            case 'store':
                // 数据列表
                $data_list = db("admin_access_store a")->join("shop b","a.storeid=b.id","left")->where($map)->order($order)->field("a.*,b.Name as storename")->paginate();
                // 分页数据
                $page = $data_list->render();

                $list_store = db("shop")->where("status=1")->column("id,name");
                // 使用ZBuilder快速创建数据表格
                return ZBuilder::make('table')
                    ->setPageTitle('业务货主') // 设置页面标题
                    ->setTabNav($tab_list, $group) // 设置tab分页
                    ->setTableName('admin_access_store') // 设置数据表名
                    ->setPrimaryKey("id")
                    ->setSearch(['id' => '编号', 'storename' => '货主名称']) // 设置搜索参数
                    ->addColumns([ // 批量添加列
                        ['id', '编号'],
                        ['storeid', '货主名称','select',$list_store],
                        ['status', '状态', 'switch'],
                        ['right_button', '操作', 'btn']
                    ])
                    ->addTopButton('add',['href' => url('storeadd',['userid'=>$userid])]) // 批量添加顶部按钮
                    ->addOrder(['listorder', 'id'])
                    ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('storeedit', ['id' => '__id__'])])
                    ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('storedelete', ['id' => '__id__'])])
                    ->setRowList($data_list) // 设置表格数据
                    ->setPages($page) // 设置分页数据
                    ->fetch(); // 渲染页面
                break;
            
        }
    }
    /**
     * 新增
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function areaadd()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AccessManage.area');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);
            
            if ($area = db("admin_access_area")->insert($data)) {
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
        $userid=input('userid');
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('业务地区新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'userid',$userid],
                ['select', 'provinceid', '省/直辖市', '', $list_province],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
            ])
            ->layout(['provinceid' => 3])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function areaedit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'AccessManage.area');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($user = db("admin_access_area")->update($data)) {
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = db("admin_access_area")->where('id', $id)->find();
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['hidden', 'userid'],
                ['select', 'provinceid', '省/直辖市', '', $list_province],
                ['radio', 'status', '状态', '', ['禁用', '启用']]
            ])
            ->layout(['provinceid' => 3])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }


    /**
     * 删除
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function areadelete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (db("admin_access_area")->delete($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
    /**
     * 新增
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function warehouseadd()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AccessManage.warehouse');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);
            
            if ($warehouse = db("admin_access_warehouse")->insert($data)) {
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
        $userid=input('userid');
        $list_warehouse = db("warehouse_list")->where("status=1 and isdel=0")->column("warehouseid,warehousename");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('业务仓库新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'userid',$userid],
                ['select', 'warehouseid', '仓库', '', $list_warehouse],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
            ])
            ->layout(['warehouseid' => 3])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function warehouseedit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'AccessManage.warehouse');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($user = db("admin_access_warehouse")->update($data)) {
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = db("admin_access_warehouse")->where('id', $id)->find();
        $list_warehouse = db("warehouse_list")->where("status=1 and isdel=0")->column("warehouseid,warehousename");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['hidden', 'userid'],
                ['select', 'warehouseid', '仓库', '', $list_warehouse],
                ['radio', 'status', '状态', '', ['禁用', '启用']]
            ])
            ->layout(['warehouseid' => 3])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function warehousedelete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (db("admin_access_warehouse")->delete($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 新增
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function storeadd()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AccessManage.store');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);
            
            if ($store = db("admin_access_store")->insert($data)) {
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
        $userid=input('userid');
        $list_store = db("shop")->where("status=1")->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('业务货主新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'userid',$userid],
                ['select', 'storeid', '货主', '', $list_store],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
            ])
            ->layout(['storeid' => 3])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function storeedit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'AccessManage.store');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($user = db("admin_access_store")->update($data)) {
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = db("admin_access_store")->where('id', $id)->find();
        $list_store = db("shop")->where("status=1")->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['hidden', 'userid'],
                ['select', 'storeid', '货主', '', $list_store],
                ['radio', 'status', '状态', '', ['禁用', '启用']]
            ])
            ->layout(['storeid' => 3])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function storedelete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (db("admin_access_store")->delete($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 新增
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function memberadd()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['memberid']=$data['memberid'][0];
            // 验证
            $result = $this->validate($data, 'AccessManage.member');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);
            
            if ($member = db("admin_access_member")->insert($data)) {
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        }
        $userid=input('userid');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('业务货主新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'userid',$userid],
                ['select','memberid','选择客户','','','','ajax','',['url'=>url('AccessManage/ajax_member'),'datakey'=>'id','dataname'=>'Name']],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
            ])
            ->layout(['memberid' => 3])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function memberedit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['memberid']=$data['memberid'][0];
            // 验证
            $result = $this->validate($data, 'AccessManage.member');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($user = db("admin_access_member")->update($data)) {
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = db("admin_access_member")->where('id', $id)->find();
        $member_list = db("Member")->where('id',$info['memberid'])->column('id,name');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['hidden', 'userid'],
                ['select','memberid','选择客户','',$member_list,'','ajax','',['url'=>url('AccessManage/ajax_member'),'datakey'=>'id','dataname'=>'Name']],
                ['radio', 'status', '状态', '', ['禁用', '启用']]
            ])
            ->layout(['memberid' => 3])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function memberdelete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (db("admin_access_member")->delete($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
    
    /**
     * 禁用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setstatus('disable');
    }

    /**
     * 启用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setstatus('enable');
    }

    public function ajax_member(){
        $search=input('q');
        $where['name']=['like',"%$search%"];
        $where['status']=1;
        $member=Db::name('member')->field('id,name')->where($where)->select();
        $memberlist=[];
        $a= 0;
        foreach($member as $value){
            $b = $a++;
            $key=$value['id'];
            $memberlist[$b]['id']=$key;
            $memberlist[$b]['name']=$value['name'];
        }
        return json(['items'=>$memberlist,'total_count'=>sizeof($memberlist)]);
    }

}